/**
 * 站点统计页面路由
 */

var router = require('express').Router();
var assertAlljs = require('../bin/util/assert-alljs');
var userTool = require('../bin/user');
var redisentityTool = require('../bin/redisentity');
var dbentityTool = require('../bin/dbentity');

router.get('/sitestatistics(.*)?', async function(req, res){
    let assert = assertAlljs(req, res);
    let checkMessage = userTool.check(req.session.user, {role: 'admin'});
    if (await assert(checkMessage))
        return;

    let t = (new Date()).getTime();
    let stat = [];
    for (let idx = 0; idx < 100; idx++)
        stat[idx] = 0;
    let timeTick1 = t - 24 * 3600 *1000;
    let timeTick2 = t - 7 * 24 * 3600 *1000;
    let timeTick3 = t - 30 * 24 * 3600 *1000;
    let timeTick4 = t - 365 * 24 * 3600 *1000;

    let sessIds = await redisentityTool.findIds('ses');
    if (await assert(sessIds instanceof Error || sessIds==null))
        return;
    let sesses = [];
    for (let sessId of sessIds)
        sesses.push(await redisentityTool.get('ses', sessId));

    for (let sess of sesses){
        let statType = 0;
        if (sess.activetime > timeTick1){
            statType = 10;
        }else if (sess.activetime > timeTick2){
            statType = 20;
        }else if (sess.activetime > timeTick3){
            statType = 30;
        }else if (sess.activetime > timeTick4){
            statType = 40;
        }
        statType += 1;
        stat[statType]++;
        if (sess.user != null){
            statType += 1;
            stat[statType]++;
        }
    }

    let users = await dbentityTool.find('user', {"signupdate":{"$gt":timeTick4}});
    if (await assert(users instanceof Error || users==null))
        return;
    for (let user of users){
        let statType = 0;
        if (user.signupdate > timeTick1){
            statType = 10;
        }else if (user.signupdate > timeTick2){
            statType = 20;
        }else if (user.signupdate > timeTick3){
            statType = 30;
        }else{
            statType = 40;
        }
        statType += 3;
        stat[statType]++;
    }

    let behaviors = await dbentityTool.find('behavior', {"t":{"$gt":timeTick4}});
    if (await assert(behaviors instanceof Error || behaviors==null))
        return;
    for (let behavior of behaviors){
        let statType = 0;
        if (behavior.t > timeTick1){
            statType = 10;
        }else if (behavior.t > timeTick2){
            statType = 20;
        }else if (behavior.t > timeTick3){
            statType = 30;
        }else {
            statType = 40;
        }
        statType += 4;
        stat[statType]++;
    }

    res.render('dyn.sitestatistics.html', {stat});
});

module.exports=router;